package com.sunwayworld.basemodule.basedata.exporttemplate.service;

import com.sunwayworld.basemodule.basedata.exporttemplate.bean.LimsExportTemplateBean;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.data.Pair;
import com.sunwayworld.framework.exception.FileException;
import com.sunwayworld.framework.exception.InvalidDataException;
import com.sunwayworld.framework.http.HttpClientManager;
import com.sunwayworld.framework.i18n.I18nHelper;
import com.sunwayworld.framework.io.file.FilePathDTO;
import com.sunwayworld.framework.io.file.FilePathManager;
import com.sunwayworld.framework.io.file.FileScope;
import com.sunwayworld.framework.support.base.service.GenericTemplateService;
import com.sunwayworld.framework.utils.FileUtils;
import com.sunwayworld.framework.utils.ServletUtils;
import com.sunwayworld.module.item.file.bean.CoreFileBean;
import com.sunwayworld.module.item.file.core.CoreFileDefaultManager;
import com.sunwayworld.module.item.file.core.CoreFileDefaultProperties;
import com.sunwayworld.module.item.file.manager.CoreFileManager;
import com.sunwayworld.module.item.file.service.CoreFileService;
import com.sunwayworld.module.item.file.utils.CoreFileUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * 导出模板优化
 */
public interface LimsGenericTemplateService<ID extends Serializable> extends GenericTemplateService<ID> {

    @Override
    default List<Pair<String, String>> getTemplatePairList() {
        return null;
    }

    @Override
    default String getDownloadUrl(String templateCode, ID id) {
        setTemplateCode(templateCode);

        LimsExportTemplateService exportTemplateService = ApplicationContextHelper.getBean(LimsExportTemplateService.class);

        CoreFileService fileService = ApplicationContextHelper.getBean(CoreFileService.class);

        // 改为从TOS服务器下载文件
        CoreFileManager fileManager = ApplicationContextHelper.getBean(CoreFileManager.class);

        LimsExportTemplateBean limsExportTemplateBean = exportTemplateService.selectByTemplateCode(templateCode);
        if (limsExportTemplateBean == null) {
            return defaultTemplateDownloadUrl(templateCode, id);
        }
        CoreFileBean coreFileBean = fileService.selectDetail(limsExportTemplateBean.getTemplateFileId());
        // 获取文件扩展名
        String fileExt = coreFileBean.getFileExt();

        FilePathDTO filePath = FilePathDTO.of(FileScope.temp.name(), "" + System.currentTimeMillis(), UUID.randomUUID().toString(), limsExportTemplateBean.getTemplateName() + "." + fileExt);
        Path path = FilePathManager.getLocalPath(filePath);
        try {
            if (CoreFileDefaultManager.isLocalFileServer()) {
                Path localPath = FilePathManager.getLocalPath(CoreFileUtils.toFilePath(coreFileBean));
                if (!localPath.equals(path)) {
                    try {
                        FileUtils.makeDirs(path);
                        Files.copy(localPath, path, StandardCopyOption.REPLACE_EXISTING);
                        if (!path.toFile().exists()){
                            return defaultTemplateDownloadUrl(templateCode, id);
                        }
                    } catch (IOException var5) {
                        throw new FileException(var5);
                    }
                }
            } else {
                HttpClientManager.getInstance().download(this.getDownloadUrl(CoreFileUtils.toFilePath(coreFileBean)), path.toFile());
            }
            this.setTemplatePath(CoreFileUtils.toFilePath(coreFileBean));
            this.initTemplateData(path, id);
            fileManager.upload(filePath, path); // 上传到文件服务器
        }
        catch (InvalidDataException e){
            throw e;
        }
        catch (Exception var10) {
            throw new FileException(var10);
        }

        return fileManager.getDownloadUrl(filePath);
    }

    default String getDownloadUrl(FilePathDTO filePath){
        CoreFileDefaultProperties properties = ApplicationContextHelper.getBean(CoreFileDefaultProperties.class);
        return CoreFileDefaultManager.isLocalFileServer() ? ServletUtils.getUrl(null, FilePathManager.getUrl(filePath)) : ServletUtils.getUrl(properties.getUrl(), FilePathManager.getUrl(filePath));
    }

    default String defaultTemplateDownloadUrl(String templateCode, ID id) {
        List<Pair<String, String>> templatePairList = this.getTemplatePairList();
        Pair<String, String> templatePair = Objects.requireNonNull(templatePairList.stream().filter(t -> t.getFirst().equals(templateCode)).findFirst().orElse(null));

        FilePathDTO filePath = FilePathDTO.of(FileScope.temp.name(), "" + System.currentTimeMillis(), UUID.randomUUID().toString(), templatePair.getSecond() + "." + getTemplateExtension());

        Path path = FilePathManager.getLocalPath(filePath);

        CoreFileManager fileManager = ApplicationContextHelper.getBean(CoreFileManager.class);

        try {
            FileUtils.makeDirs(path);

            URL resource = this.getClass().getResource("");
            if (FileUtils.isInJarURL(resource)) {
                InputStream is = this.getClass().getResourceAsStream("templates/" + templateCode + "." + getTemplateExtension());
                Files.copy(is, path, StandardCopyOption.REPLACE_EXISTING);
            } else {
                Path templatePath = new File(resource.getPath()).toPath().resolve("templates").resolve(templateCode + "." + getTemplateExtension());
                Files.copy(templatePath, path, StandardCopyOption.REPLACE_EXISTING);
            }
            if (!path.toFile().exists()){
                throw new InvalidDataException(I18nHelper.getMessage("EXPORT.EXCEPTION.DEFAULT.TEMPLATE.IS.NULL"));
            }
            initTemplateData(path, id);

            fileManager.upload(filePath, path);
        } catch (IOException ioe) {
            throw new FileException(ioe);
        }

        return fileManager.getDownloadUrl(filePath);
    }

    default void setTemplateCode(String templateCode) {

    }

    @Override
    default void initTemplateData(Path path, ID id) {
    }

    default void setTemplatePath(FilePathDTO templatePath) {

    }
}
